package com.magic.item.controller;

import com.magic.item.pojo.Category;
import com.magic.item.service.CategoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lan.jianyuan
 * @create 2021-01-04-10:57
 */
@Controller
@RequestMapping("category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    /**
     * 根据parentId查询子节点
     * @param pid
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<Category>> queryCategoriesByPid(@RequestParam(value = "pid", defaultValue = "0")Long pid) {
        if (pid == null || pid < 0) {
            // pid为null或者小于等于0，响应400 : 参数不合法
            return ResponseEntity.badRequest().build();
        }
        // 执行查询操作
        List<Category> categoryList = this.categoryService.queryCategoryListByParentId(pid);
        if (CollectionUtils.isEmpty(categoryList)) {
            // 返回结果集为空，响应404
            return ResponseEntity.notFound().build();
        }
        // 响应200
        return ResponseEntity.ok(categoryList);
    }
    /**
     * 添加商品分类
     * @param category  从前台传来的数据
     * @return
     */
    @PostMapping("add")
    public ResponseEntity<Void> addCategory(@RequestBody Category category) {
        categoryService.addCategory(category);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 修改类别
     * @param category
     */
    @PutMapping("update")
    public ResponseEntity<Void> updateCategory(@RequestBody Category category) {
        categoryService.updateCategory(category);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    
    /**
     * 删除类别
     * @param id
     * @return
     */
    @RequestMapping("delete")
    public ResponseEntity<Void> deleteCategory(@RequestParam("id")Long id) {
        categoryService.deleteCategory(id);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 根据商品分类id查询名称
     * @param ids 要查询的分类id集合
     * @return 多个名称的集合
     */
    @GetMapping
    public ResponseEntity<List<String>> queryNameByIds(@RequestParam("ids")List<Long> ids) {
        List<String> names = this.categoryService.queryNamesByIds(ids);
        if (CollectionUtils.isEmpty(names)) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(names);
    }
}
